package com.veo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.veo.bean.User;
import com.veo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public String doLogin(@RequestParam("username") String name, @RequestParam("password") String pwd, HttpServletRequest request){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",name);
        if (userService.getOne(wrapper) != null && "666".equals(pwd)){
            User user = new User();
            user.setUserName(name);
            request.getSession().setAttribute("loginUser",user);
            return "redirect:index";
        }
        request.setAttribute("msg","用户名或密码错误");
        return "login";
    }

    @GetMapping("/loginOut")
    public String doLoginOut(HttpServletRequest request){
        request.getSession().invalidate();
        return "login";
    }

    @GetMapping("/dynamic_table")
    public String getTableData(Model model, @RequestParam(value = "pn",defaultValue = "1") Long currentPage){
        Page<User> page = new Page(currentPage,2);
        Page<User> userPage = userService.page(page);
        List<User> list = userPage.getRecords();
        list.forEach(System.out::println);
        model.addAttribute("list",userPage);
        return "table/dynamic_table";
    }

    @GetMapping("/delUser")
    public String delUser(@RequestParam("uid")Integer uid, @RequestParam(value = "pn",defaultValue = "1")Long pn, RedirectAttributes ra){

        userService.removeById(uid);
        ra.addAttribute("pn",pn);
        return "redirect:/dynamic_table";
    }


}
